package com.jsti.ccp.error.handler;

import com.jsti.ccp.error.exception.TicRuntimeException;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@Component
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        String feignUrl = response.request().url();
        int status = response.status();
        if (status >= 400 && status <= 499) {
            // 客户端错误，根据状态码和响应体处理
            if (status == 400) {
                // 400 Bad Request
                String errorMessage = extractErrorMessage(response);
                return new TicRuntimeException(status, "Bad Request: " + errorMessage);
            } else if (status == 404) {
                // 404 Not Found
                return new TicRuntimeException(status, "Resource not found");
            } else if (status == 403) {
                // 403 Forbidden
                return new TicRuntimeException(status, "Access forbidden");
            } else {
                // 其他客户端错误
                return new TicRuntimeException(status, "Client error: " + status);
            }
        } else if (status >= 500 && status <= 599) {
            // 服务端错误，根据状态码和响应体处理
            if (status == 500) {
                // 500 Internal Server Error
                String errorMessage = extractErrorMessage(response);
                return new TicRuntimeException(status, "Internal server error: " + errorMessage);
            } else {
                // 其他服务端错误
                return new TicRuntimeException(status, "Server error: " + status);
            }
        }

        // 默认情况返回Feign默认的异常处理
//        log.error();//添加日志对默认情况的筛选及监控，后续支持
        return defaultDecoder(methodKey, response);
    }

    private Exception defaultDecoder(String methodKey, Response response) {
        // 使用Feign默认的异常处理
        return new ErrorDecoder.Default().decode(methodKey, response);
    }

    private String extractErrorMessage(Response response) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().asInputStream(), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        } catch (IOException e) {
            return "Error reading response body";
        }
    }
}
